import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;


public class MyClassLoader extends ClassLoader {
	// jar文件所在的路径
	private String jarPath;
	
	//jar文件
	private JarFile jarFile;
	
	public MyClassLoader(String jarPath) {
		this.jarPath = jarPath;
	}
	
	public MyClassLoader(JarFile jarFile) {
		this.jarFile = jarFile;
	}
	
	/**
	 * 从某个jar包中加载某个class
	 */
	public void loadAllClass() throws ClassNotFoundException {
		
        try  
        {   
        	JarFile jarFile = this.jarFile == null ? new JarFile(jarPath) : this.jarFile;
        	Enumeration<JarEntry> enumeration = jarFile.entries();
        	while(enumeration.hasMoreElements()) {
        		JarEntry jarEntry = enumeration.nextElement();
        		if(jarEntry.getName().endsWith(".class")) {
        		    int  size = (int)jarEntry.getSize(); 
        			InputStream in = jarFile.getInputStream(jarEntry);  
        			byte[] b = new byte[size];
        			int offset = 0;
        			
        			while(true) {
        				int length = in.read(b,offset,size-offset);   
                        offset += length;   
                        if (offset >= size)   
                        {   
                            break;    
                        }   
        			}
        			String className = jarEntry.getName().substring(0,jarEntry.getName().lastIndexOf(".")).replace("/", ".");
        			Class<?> clazz = defineClass(className, b, 0, size); 
        			Object object = clazz.newInstance();
        			in.close();
        		}
        	}
              
        } catch(Exception e) {
        	
        }
        finally {
        	
        }
        
	}
	
	public static void main(String args[]) throws Exception {
		JarFile jarFile = new JarFile("D:/auto_build/jar.jar");
		MyClassLoader loader = new MyClassLoader(jarFile);
		loader.loadAllClass();
	}
	
}
